<template>
  <div class="AcceptAndHearACase" v-loading="loading">
    <el-form :inline="true" :model="searchData">
      <el-form-item label="装修程度：">
        <el-select v-model="searchData.renovation" placeholder="请选择装修程度">
          <el-option
            :label="item"
            :value="index"
            v-for="(item, index) in renovationList"
            :key="index"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="价格：">
        <el-input
          v-model="searchData.price"
          placeholder="请输入价格"
        ></el-input>
      </el-form-item>
      <el-form-item label="房源状态：">
        <el-select v-model="searchData.status" placeholder="请选择房源状态">
          <el-option label="未出租" :value="0"></el-option>
          <el-option label="已出租" :value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          @click="serach"
          class="btn-search"
          >筛选</el-button
        >
        <el-button icon="el-icon-refresh-left" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button
      type="primary"
      icon="el-icon-plus"
      @click="newBuilt"
      class="btn-export"
      >添加房源</el-button
    >
    <el-table
      :data="tableData"
      style="width: 100%"
      height="84%"
      :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
    >
      <el-table-column type="index" label="序号" align="center">
      </el-table-column>
      <el-table-column prop="createTime" label="创建日期" align="center">
      </el-table-column>
      <el-table-column label="房源图片" align="center" prop="houseImg">
        <template slot-scope="scope">
          <el-popover placement="right" trigger="hover">
            <img
              :src="scope.row.houseImg"
              style="width: 150px; height: 150px"
            />
            <img
              slot="reference"
              :src="scope.row.houseImg"
              style="max-height: 80px; max-width: 80px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="房源名字" align="center">
      </el-table-column>
      <el-table-column prop="address" label="地址" align="center" width="500">
      </el-table-column>
      <el-table-column prop="houseType" label="房型" align="center">
      </el-table-column>
      <el-table-column prop="area" label="面积" align="center">
      </el-table-column>
      <el-table-column prop="renovation" label="装修程度" align="center">
        <template slot-scope="scope">
          {{ renovationList[scope.row.renovation] }}
        </template>
      </el-table-column>
      <el-table-column prop="floor" label="楼层" align="center">
      </el-table-column>
      <el-table-column prop="price" label="价格" align="center">
        <template slot-scope="scope">
          {{ scope.row.price + "元/月" }}
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" align="center">
        <template slot-scope="scope">
          {{ scope.row.status ? "已出租" : "未出租" }}
        </template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="150" align="center">
        <template slot-scope="scope">
          <el-button
            @click="handleClick(scope.row)"
            type="text"
            size="medium"
            style="margin-right: 10px"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="好的"
            cancel-button-text="不用了"
            icon="el-icon-info"
            icon-color="red"
            title="确定删除吗？"
            @confirm="deleteConfirm(scope.row)"
          >
            <el-button
              slot="reference"
              type="text"
              size="medium"
              style="color: red"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <div class="AcceptAndHearACase-content-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 30, 40]"
        :page-size="pageSize"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="isNew ? '添加' : '编辑'"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      v-loading="loading"
    >
      <el-form
        :model="formData"
        label-width="100px"
        :rules="formRules"
        ref="form"
      >
        <el-form-item label="上传房源图片：" prop="houseImg">
          <el-upload
            class="avatar-uploader"
            action="http://43.139.235.169:8081/cos/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="formData.houseImg"
              :src="formData.houseImg"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="房源名字：" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入房源名字"
          ></el-input>
        </el-form-item>
        <el-form-item label="地址：" prop="address">
          <el-input
            v-model="formData.address"
            placeholder="请输入地址"
          ></el-input>
        </el-form-item>
        <el-form-item label="房型：" prop="houseType">
          <el-input
            v-model="formData.houseType"
            placeholder="请输入房型"
          ></el-input>
        </el-form-item>
        <el-form-item label="面积：" prop="area">
          <el-input v-model="formData.area" placeholder="请输入面积"></el-input>
        </el-form-item>
        <el-form-item label="装修程度：" prop="renovation">
          <el-select v-model="formData.renovation" placeholder="请选择装修程度">
            <el-option
              :label="item"
              :value="index"
              v-for="(item, index) in renovationList"
              :key="index"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="楼层：" prop="floor">
          <el-input
            v-model="formData.floor"
            placeholder="请输入楼层"
          ></el-input>
        </el-form-item>
        <el-form-item label="价格：" prop="price">
          <el-input
            v-model="formData.price"
            placeholder="请输入价格"
          ></el-input>
        </el-form-item>
        <el-form-item label="房源状态" prop="state">
          <el-radio-group v-model="formData.state">
            <el-radio :label="0">未出租</el-radio>
            <el-radio :label="1">已出租</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "VolunteerReview",
  data() {
    const validateRenovation = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请选择装修程度"));
      } else {
        callback();
      }
    };
    const validateState = (rule, value, callback) => {
      if (!value && value != 0) {
        callback(new Error("请选择房源状态"));
      } else {
        callback();
      }
    };
    return {
      //加载状态
      loading: false,
      //分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchData: {
        renovation: "",
        price: "",
        status: "",
      },
      renovationList: ["毛坯", "精装修", "简装修"],
      tableData: [],
      dialogVisible: false,
      formData: {},
      isNew: false,
      //弹窗校验规则
      formRules: {
        houseImg: [
          { required: true, trigger: "blur", message: "请上传房源图片" },
        ],
        name: [{ required: true, trigger: "blur", message: "请输入房源名字" }],
        address: [{ required: true, trigger: "blur", message: "请输入地址" }],
        houseType: [{ required: true, trigger: "blur", message: "请输入房型" }],
        area: [{ required: true, trigger: "blur", message: "请输入面积" }],
        price: [{ required: true, trigger: "blur", message: "请输入价格" }],
        floor: [{ required: true, trigger: "blur", message: "请输入楼层" }],
        renovation: [
          { required: true, trigger: "change", validator: validateRenovation },
        ],
        state: [
          { required: true, trigger: "change", validator: validateState },
        ],
      },
    };
  },
  mounted() {
    this.getHousingResourcesInfoList();
  },
  methods: {
    //获取数据
    async getHousingResourcesInfoList(renovation, price, state) {
      this.loading = true;
      const res = await this.$api.getHousingResourcesInfoList({
        pageIndex: this.currentPage,
        pageSize: this.pageSize,
        renovation: renovation,
        price: price,
        state: state,
      });
      // console.log(res);
      this.tableData = res.data.records;
      this.total = res.data.total;
      this.loading = false;
    },
    //查询数据
    serach() {
      this.getHousingResourcesInfoList(
        this.searchData.renovation,
        this.searchData.price,
        this.searchData.status
      );
    },
    //重置按钮
    reset() {
      this.searchData = {
        renovation: "",
        price: "",
        status: "",
      };
      this.getHousingResourcesInfoList();
    },
    //新建
    newBuilt() {
      this.formData = {
        deviceImg: "",
      };
      this.isNew = true;
      this.dialogVisible = true;
    },
    //编辑
    handleClick(row) {
      // console.log(row);
      this.formData = row;
      this.isNew = false;
      this.dialogVisible = true;
    },
    //编辑或者新建弹窗确认
    confirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.loading = true;
          if (this.isNew) {
            //新建
            this.$api.addHousingResourcesInfo(this.formData).then((res) => {
              if (res.code === 0) {
                this.loading = false;
                this.dialogVisible = false;
                this.reset();
                this.$message({
                  message: "添加成功！",
                  type: "success",
                });
              }
            });
          } else {
            //编辑
            this.$api.updateHousingResourcesInfo(this.formData).then((res) => {
              // console.log(res);
              if (res.code === 0) {
                this.loading = false;
                this.dialogVisible = false;
                this.reset();
                this.$message({
                  message: "修改成功！",
                  type: "success",
                });
              }
            });
          }
        } else {
          this.$message({
            message: "请输入完整内容",
            type: "error",
          });
          return;
        }
      });
    },
    //关闭弹窗的方法
    handleClose() {
      this.dialogVisible = false;
    },
    //删除
    async deleteConfirm(row) {
      const res = await this.$api.deleteHousingResourcesInfoById({
        id: row.id,
      });
      if (res.code === 0) {
        this.serach();
        this.$message({
          message: "删除成功！",
          type: "success",
        });
      }
    },
    //上传成功
    handleAvatarSuccess(res, file) {
      this.formData.houseImg = res.resultObj;
      this.loading = false;
      //移除图片表单校验结果
      this.$refs.form.clearValidate("houseImg");
    },
    //上传前
    beforeAvatarUpload(file) {
      this.loading = true;
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }

      this.loading = isJPG && isLt2M;
      return isJPG && isLt2M;
    },
    //页数
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      let that = this;
      that.pageSize = val;
      that.serach();
    },
    //翻页
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      let that = this;
      that.currentPage = val;
      that.serach();
    },
  },
};
</script>

<style lang="scss" scoped>
.btn-search {
  background: #409eff;
  border: 1px solid #409eff;
  &:hover {
    opacity: 0.8;
  }
}
.btn-export {
  width: 120px;
  background: #409eff;
  border: 1px solid #409eff;
  margin-bottom: 20px;
  &:hover {
    opacity: 0.8;
  }
}
.avatar-uploader ::v-deep(.el-upload) {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep(.el-upload):hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.AcceptAndHearACase {
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  height: 100%;
  width: 100%;
  background-color: #ffffff;
  border-radius: 4px;
  padding: 24px;
  overflow: hidden;

  &-content {
    width: 100%;
    flex: 1;
    overflow: hidden;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    &-table {
      width: 100%;
      flex: 1;
      overflow-y: auto;
    }
    &-page {
      display: flex;
      justify-content: flex-end;
      width: 100%;
      margin-top: 16px;
      .el-pagination {
        padding: 0;
        .el-pagination__total {
          line-height: 40px;
          font-size: 16px;
          color: rgba(0, 0, 0, 0.8);
        }
      }
    }
  }
}
</style>

